package com.skillworld.webapp.web.pages.rest.school;

import java.util.List;

import org.apache.tapestry5.annotations.ContentType;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;

import com.skillworld.webapp.model.courseservice.CourseService;
import com.skillworld.webapp.model.lesson.Lesson;
import com.skillworld.webapp.model.util.PermissionDeniedException;
import com.skillworld.webapp.web.util.ErrorMessages;
import com.skillworld.webapp.web.util.Parameter;
import com.skillworld.webapp.web.util.UserSession;

import es.udc.pojo.modelutil.exceptions.InstanceNotFoundException;

@ContentType("text/xml")
public class CreateLesson {
	
	@SuppressWarnings("unused")
    @Property
    private String errorMessage = null;
   
	@SuppressWarnings("unused")
	@Property
	private Lesson lesson;
	
    @Inject
    private CourseService courseService;
    
    @SessionState(create=false)
    private UserSession userSession;
   
    private boolean userSessionExists;
    
    @Inject
    private Request request;

	
    void onPassivate()
    {
        return;
    }
    
    void onActivate()
    {        
        if (!userSessionExists)
        {
            errorMessage = ErrorMessages.NOT_LOGGED_IN;
            return;
        }
        
        String courseParam = request.getParameter("course");
        String name = request.getParameter("name");
        String description = request.getParameter("desc");
        String tutsParam = request.getParameter("tuts");
        
        if (courseParam ==null || name== null || description == null 
                || tutsParam == null)
        { 
            errorMessage = ErrorMessages.INVALID_ARGUMENTS;
            return;
        }
        
        try
        {
            long courseId = Long.parseLong(courseParam);
            List<Long> tutorialsIds = Parameter.commaSepIds(tutsParam);
            lesson = courseService.createLesson(courseId, userSession.getUserId(), 
                                                    name, description, tutorialsIds);
        }
        catch(NumberFormatException e)
        { this.errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
        catch (InstanceNotFoundException e)
        { this.errorMessage = ErrorMessages.COURSE_NOT_FOUND; } 
        catch (PermissionDeniedException e) 
        { this.errorMessage = ErrorMessages.PERMISSION_DENIED; }
    }
}
    

